package com.cy.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.PageList;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.cy.bfzcommons.mapper.UserMapper;
import com.cy.bfzcommons.pojo.PassWord;
import com.cy.bfzcommons.pojo.User;
import com.cy.bfzcommons.service.UserService;
import com.cy.bfzcommons.web.util.jwt.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    //新增用户
    @Transactional
    public String addUser(User user){
//        if(checkUser( user ) == null ) return "非法填写";                                                   //判断用户合法性
//        String password = user.getPassword().trim();
//        String salt = UUID.randomUUID().toString().replace("-","");                      //创建盐值
//        SimpleHash sh = new SimpleHash ("MD5" , password , salt ,1);             //密码加密
//        String md5password = sh.toHex ();
//        user.setSalt( salt ).setPassword( md5password );                                                   //添加密码与盐值
//        int i = userMapper.insert( user );
//        if( i == 1 ){
//            return null;
//        }else{
//            return "新增失败";
//        }
        return null;
    }

    //查询用户(小心密码泄露)(已解决)
    public PageList getUser(PageList pageList){
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        queryWrapper.select("user_id","user_name","email","portrait","nick_name","birthday",
//                "phone","members","address","created","modified");
//        queryWrapper.like( StringUtils.hasLength( pageList.getQuery() ),"user_name" , pageList.getQuery());               //姓名模糊查询         //地址模糊查询
//        Page<User> page = new Page<>(pageList.getPageNum(),pageList.getPageSize());
//        IPage<User> iPage = userMapper.selectPage(page, queryWrapper);
//        pageList.setList(iPage.getRecords()).setTotal(page.getTotal());
//        return pageList;
        return null;
    }

    //通过id查询用户(注意密码泄露)
    @Override
    public User selectById(Integer id) {
        return userMapper.selectById(id);
    }

    //更新用户信息
    @Transactional
    @Override
    public String updataUser(User user) {
        if ( user.getUserId() == null || user.getUserId() == 0 )  return "获取用户错误";
        user.setPassword(null).setSalt(null).setMembers(null);                                      //盐值 密码 会员不能修改
        int i = userMapper.updateById(user);
        if (i == 1) {
            return null;
        } else {
            return "更新用户失败";
        }
    }

    //更改密码
    @Transactional
    @Override
    public String updataPassWord( PassWord passWord ) {
//        Integer userId = passWord.getUserId();
//        if ( userId == null || userId == 0)  return "获取用户失败";
//        String password = passWord.getPassword().trim();
//        String newpassword = passWord.getNewpassword().trim();
//        if( !StringUtils.hasLength( password ) ) return "请正确填写密码";
//        if( !StringUtils.hasLength( newpassword ) ) return "请正确填写密码";
//        if( passWord.equals( newpassword ) ) return "新旧密码不能一样哦";
//        User user = userMapper.selectById( passWord.getUserId() );                                      //根据id查询用户
//        String saltold = user.getSalt();                                                                //获取盐值
//        SimpleHash shold = new SimpleHash("MD5" , password , saltold ,1);     //获取用户的旧密码
//        String md5pwOld = shold.toHex();
//        String oldpassword = user.getPassword();                                                        //获取数据库的旧密码
//        if( oldpassword.equals( md5pwOld ) ){                                                           //判断密码是否一样
//            User user1 = new User();                                                                    //创建更新对象
//            String newsalt = UUID.randomUUID().toString().replace("-","");
//            SimpleHash sh = new SimpleHash("MD5" , newpassword, newsalt ,1);  //新密码加密
//            String newmd5 = sh.toHex();
//            user1.setUserId( userId ).setSalt( newsalt ).setPassword( newmd5 );
//            userMapper.updateById( user1 );
//            return null;
//        }else{
//            return "密码修改失败";
//        }
        return null;
    }
    //更新会员状态
    @Transactional
    @Override
    public String updataMembers(Integer userId, Integer members) {
        User user = new User();
        user.setUserId(userId).setMembers(members);
        int i = userMapper.updateById(user);
        if(i==1) return null;
        return "更改失败";
    }
    //后台更改会员状态
    @Override
    public String updateUserBack(User user) {
        if(user.getUserId() <= 0||user.getUserId() == null) return "获取账号失败";
        int i = userMapper.updateById(user);
        if(i == 0) return "更新失败";
        return null;
    }
    //前台登录
    @Override
    public String Login(User user) {
        //有空做一下非法验证....
//        String email = user.getEmail();
//        User usersql = userMapper.selectByEmail(email);
//        if(usersql==null) return null;                                          //"没有该用户";
//        String password = user.getPassword();
//        String passwordsql = usersql.getPassword();
//        String salt = usersql.getSalt();
//        String md5password = new SimpleHash("MD5",password,salt,1).toHex();
//        if(!md5password.equals(passwordsql)) return null;                       //"密码错误";
//        //正确并返回一个cooke
//        Long userId = Long.valueOf(usersql.getUserId());
//        log.info("用户ID:{}",userId);
//        String token = JwtUtil.createToken(userId);
//        log.info("token:{}",token);
//        return token;
        return null;
    }
    //修改用户
    @Override
    public String updataUserbefore(User user) {
        if ( user.getUserId() == null || user.getUserId() == 0 )  return "获取用户错误";
        user.setPassword(null).setSalt(null).setMembers(null).setEmail(null).setUserName(null);                                      //盐值 密码 会员不能修改
        System.out.println(user);
        int i = userMapper.updateById(user);
        if (i == 1) {
            return null;
        } else {
            return "更新用户失败";
        }
    }
    @Override
    public User selectuserByemail(String email) {
        if(!email.matches("^[a-zA-Z0-9-_]+@[a-zA-Z0-9-_]+\\.[a-zA-Z0-9-_]+$")) return null;
        User user = userMapper.selectByEmail(email);
        System.out.println(user);
        return user;
    }
    //注册新用户
    @Transactional
    @Override
    public Integer signin(User user) {
//        User user2 = selectuserByemail(user.getEmail());
//        if(user2!=null) return null;
//        User user1 = new User();
//        if(!user.getEmail().matches("^[a-zA-Z0-9-_]+@[a-zA-Z0-9-_]+\\.[a-zA-Z0-9-_]+$")) return null;
//        user1.setEmail(user.getEmail());
//        String password = user.getPassword().trim();
//        String salt = UUID.randomUUID().toString().replace("-","");                      //创建盐值
//        SimpleHash sh = new SimpleHash ("MD5" , password , salt ,1);             //密码加密
//        String md5password = sh.toHex ();
//        user1.setSalt( salt )
//                .setPassword( md5password )
//                .setUserName(user.getUserName())
//                .setNickName("芜湖~")
//                .setMembers(0)
//                .setPortrait("http://localhost:8091/upload/dog.gif");
//        userMapper.insert(user1);
//        Integer userId = user1.getUserId();
//        return userId;
        return null;
    }

    @Override
    public String selectUserName(Integer userId) {
        String userName = userMapper.selectUserName(userId);
        return userName;
    }


    //检查user合法性(缺少邮箱验证 电话号码与邮箱可以重复吗?)
    public User checkUser(User user){
        if(!StringUtils.hasLength(user.getUserName())) return null;                         //判断名字是否为空
        if(!StringUtils.hasLength(user.getPassword())) return null;                         //判断密码是否为空
        if(!StringUtils.hasLength(user.getEmail())) return null;                            //判断邮箱是否为空
//        if(!StringUtils.hasLength(user.getPortrait())) return null;                         //判断是头像地址否为空
        if(!StringUtils.hasLength(user.getNickName())) return null;                         //判断是昵称否为空
        if(user.getBirthday()==null) return null;                                           //判断生日是否为空
        if(!String.valueOf(user.getPhone()).matches("^1[3-9]\\d{9}$")) return null;   //判断电话号码是否合法
        return user;
    }




}
